package com.pym.bs.utils;

import com.pym.bs.dto.UserDetailsDTO;
import com.pym.bs.enums.ResultEnum;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


public class UserDetailsUtils {

    public static UserDetailsDTO getUserDetailsDTO() {
        UserDetailsDTO userDetailsDTO = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            throw new UsernameNotFoundException(ResultEnum.UNAUTHORIZED.getMessage());
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetailsDTO) {
            userDetailsDTO = (UserDetailsDTO) principal;
        }
        return userDetailsDTO;
    }
}
